<template>
  <div>
    <div @click="openModal">
      店铺上新
    </div>
    <a-modal 
      v-model:open="showModal"
      title="店铺上新"
      width="70vw"
    >
      <template #footer>
      </template>
      <div v-if="isinit" style="display: flex;align-items: center; justify-content: center;">
        <a-progress type="circle" :percent="progressPercent" />
      </div>
      <div v-else>
        <div style="display: flex; justify-content: flex-end;">
          <div style="color: #666666;font-size: 12px;display: inline-block;line-height: 2;padding-right: 10px;">
            已加载 {{ currentTotal }} 条评论，共 {{ total }} 条
          </div>
          <a-button v-if="loading" size="small" type="primary" @click="load('stop')">暂停加载</a-button>
          <a-button v-else size="small" type="primary" @click="load('load')">继续加载</a-button>
        </div>
        <base-table
          title="评论分析" 
          :scroll="{y:500}" 
          size="small" 
          :data-source="dataList" 
          :columns="columns"
        >
          <template #productNameSlot="record">
            <div style="display: flex;flex-direction: row;align-items: center;">
              <a-tooltip>
                <template #title>
                  <img style="width: 200px;height: 200px;margin-right: 10px;object-fit: contain;" :src="record.uprightImg" alt="">
                </template>
                <img style="width: 36px;height: 36px;margin-right: 10px;" :src="`${record.uprightImg}_sum.jpg`" alt="">
              </a-tooltip>
              <div style="display: flex;flex-direction: column;">
                <a-tooltip>
                  <template #title>
                    {{ record.title }}
                  </template>
                  <div class="text-ellipsis" style="max-width: 200px;">
                    {{ record.title }}
                  </div>
                </a-tooltip>
                <div>
                  ID: {{ record.item_id }}
                </div>
              </div>
            </div>
          </template>
          <template #realSalesSlot="record">
            {{ parseInt(record.realSales) }}
          </template>
        </base-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue';
import {isLogin} from '~/logic'
import { $itemType } from '~/contentScripts/views/tao/detail/components/commodityData/index'
import {TRequest} from "~/utils/ali/PCRequest";
import { appsearchType, ItemsArrayType } from '~/contentScripts/views/tao/detail/components/storeRelated/newShop/appsearch'

const emit = defineEmits(['login'])
const __option = getCurrentInstance()?.appContext.provides.option;
const getItem = () => {
  const instance = getCurrentInstance();
  const item = (instance?.proxy as { $item?: any }).$item ?? {};
  return item;
}
const item = getItem()

let timerId: ReturnType<typeof setTimeout>;
const isinit = ref(false)
const loading = ref(false)
const progressPercent = ref(0) 
const total = ref(0)
const currentTotal = ref(0)
const page = ref(0)
const showModal = ref(false)
const dataList = ref<ItemsArrayType[]>([])
const columns = ref([
  {
    dataIndex: 'productName',
    title: '商品名称',
    width: 300,
    dataType: 'custom',
    fixed: 'left',
    slot: 'productNameSlot',
  },
  {
    dataIndex: 'price',
    title: '价格',
    fixed: 'left',
  },
  {
    dataIndex: 'priceWap',
    title: '促销价',
  },
  {
    dataIndex: 'realSales',
    title: '付款人数',
    dataType: 'custom',
    slot: 'realSalesSlot',
  },
])

const getData = async () => {
  page.value ++
  const res: $itemType = await item.getDetail()
  const res2: appsearchType = await TRequest.getAppsearch(res.seller.userId, page.value)
  console.log("🚀 ~ getData ~ res2:", res2)
  
  if (!res2.itemsArray) {
    isinit.value = false
    loading.value = false
    stopTimerAndResetDataCount()
    return 
  }
  dataList.value.push(...res2.itemsArray)
  console.log("🚀 ~ getData ~ dataList.value :", dataList.value )
  currentTotal.value += dataList.value.length
  progressPercent.value = currentTotal.value
  total.value = parseInt(res2.totalPage)
  if (isinit.value) {
    initTimeGetData()
  }
}

// 初始化获取数据
const initTimeGetData = () => {
  console.log("🚀 ~ initTimeGetData ~ currentTotal.value < 100 && currentTotal.value < total.value:", currentTotal.value < 100 && currentTotal.value < total.value)
  if (currentTotal.value < 100 && currentTotal.value < total.value) {
    timerId = setTimeout(() => {
      getData();
    }, 3000);
  }else {
    isinit.value = false
  }
}

// 定时获取数据
const timeGetData = () => {
  if (currentTotal.value >= total.value) {
    return stopTimerAndResetDataCount()
  } else {
    timerId = setTimeout(() => {
      getData();
      timeGetData();
    }, 500);
  }
}
// 停止获取数据 重置计时器
const stopTimerAndResetDataCount = () => {
  loading.value = false
  clearTimeout(timerId);
};

const init = () => {
  if (isLogin({emit}, __option)) {
    isinit.value = true
    getData()
  }
} 

const openModal = () => {
  showModal.value = true
  init()
}

const load = (type: 'stop' | 'load') => {
  if(type ==='stop') {
    loading.value = false
    stopTimerAndResetDataCount()
  }else {
    loading.value = true
    timeGetData()
  }
}
</script>

<style lang="less" scoped>
.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>